package test.democlient.service;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import test.democommon.rpc.TestGrpc;
import test.democommon.rpc.TestServiceProto;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Slf4j
@Service
public class GrpcClientService {

    @Value("${grpc.client.host:localhost}")
    private String grpcHost;

    @Value("${grpc.client.port:9090}")
    private int grpcPort;

    private  ManagedChannel channel;
    private TestGrpc.TestBlockingStub blockingStub;

    @PostConstruct
    public void init() {
        // 创建gRPC通道
        channel = ManagedChannelBuilder.forAddress(grpcHost, grpcPort)
                .usePlaintext()
                .build();
        
        // 创建阻塞式客户端存根
        blockingStub = TestGrpc.newBlockingStub(channel);
        
        log.info("gRPC客户端已初始化，连接到 {}:{}", grpcHost, grpcPort);
    }

    @PreDestroy
    public void destroy() {
        if (channel != null && !channel.isShutdown()) {
            channel.shutdown();
            log.info("gRPC客户端连接已关闭");
        }
    }

    /**
     * 调用sayHello方法
     */
    public String callSayHello(String context, int number) {
        try {
            // 构建请求
            TestServiceProto.TestRequest request = TestServiceProto.TestRequest.newBuilder()
                    .setContext(context)
                    .setNumber(number)
                    .build();

            log.info("发送gRPC请求: context={}, number={}", context, number);

            // 发送请求并获取响应
            TestServiceProto.TestResponse response = blockingStub.sayHello(request);
            
            String responseMessage = response.getMessage();
            log.info("收到gRPC响应: {}", responseMessage);
            
            return responseMessage;
        } catch (Exception e) {
            log.error("gRPC调用失败", e);
            return "调用失败: " + e.getMessage();
        }
    }

} 